﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using RN.ERP.Web.Utilities;
using System.Configuration;
using System.IO;

namespace RN.ERP.Web.UserControl
{
    public partial class UCPsnExpertInfo : RN.ERP.Web.Utilities.BaseUserControl
    {
        #region  公共属性
        /// <summary>
        /// pdf下载地址
        /// </summary>
        protected string PdfDwonUrl
        {
            get
            {
                if (ConfigurationManager.AppSettings["PdfDwonUrl"] != null)
                {
                    return ConfigurationManager.AppSettings["PdfDwonUrl"];
                }
                return "";
            }
        }
        /// <summary>
        /// 窗口类型
        /// </summary>
        public int WindowModel
        {
            get;
            set;
        }
        /// <summary>
        /// 页面编辑状态
        /// </summary>
        protected int EditStatus
        {
            get;
            set;
        }

        /// <summary>
        /// 系统标识
        /// </summary>
        protected string AppId
        {
            get
            {
                return ConfigurationManager.AppSettings["AppId"];
            }
        }

        /// <summary>
        /// 上次请求地址
        /// </summary>
        protected string UrlBack
        {
            get;
            set;
        }
        /// <summary>
        /// 显示状态(1:内页审核2:浏览信息)
        /// </summary>
        private int ShowStatus = 0;

        /// <summary>
        /// 用户类型
        /// </summary>
        protected string UserRole
        {
            get
            {
                return UserInfo.RoleType;
            }
        }
        /// <summary>
        /// 用户角色
        /// </summary>
        protected string RoleId
        {
            get
            {
                return UserInfo.RoleId;
            }
        }
        //当前市场
        protected string CurrentArea
        {
            get
            {
                return UserInfo.CurrentArea;
            }
        }
        //当前登录用户Guid
        private string CorpUserGuid
        {
            get
            {
                return UserInfo.CorpUserGuid;
            }
        }
        /// <summary>
        /// 是否显示关闭按钮
        /// </summary>
        protected int CloseBtnShow = 0;
        /// <summary>
        /// 窗口提示消息
        /// </summary>
        protected string Message = string.Empty;
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParams();
                Initial();
                BindDropDownList();
               
                CheckFlowCode();
            }
        }

        #region 页面初始化

        /// <summary>
        /// 获取传递参数
        /// </summary>
        private void GetParams()
        {
            Guid empGuid = Guid.NewGuid();//生成的人员Guid
            int typeFlag = -1;//人员类型
            int opt = 0;//编辑状态标识
            
            if (!string.IsNullOrEmpty(Request.QueryString["empGuid"]))
            {
                if (Guid.TryParse(Request.QueryString["empGuid"], out empGuid))
                {
                    hdStatus.Value = "1";//修改标识
                }
            }
            ////如果没有用户信息 则处于注册页面
            else if (UserInfo != null)
            {
                if(Guid.TryParse(UserInfo.CorpUserGuid,out empGuid))
                {
                    ////修改标识
                    hdStatus.Value = "1";
                }
            }

            hdEmpGuid.Value = empGuid.ToString();
            //安全考核证guid
            hdempExtGuid.Value = Guid.NewGuid().ToString();
            ////人员类型
            if (!string.IsNullOrEmpty(Request.QueryString["typeFlag"]))
            {
                int.TryParse(Request.QueryString["typeFlag"], out typeFlag);
            }
            ////可编辑显示状态（1：内容不可编辑，2：所有不可用）
            if (!string.IsNullOrEmpty(Request.QueryString["opt"]))
            {
                int.TryParse(Request.QueryString["opt"], out opt);
            }
            hdTypeFlag.Value = typeFlag.ToString();
            hdCorpGuid.Value = CorpUserGuid;
            HdAreaCode.Value = CurrentArea;
            ///是否显示关闭按钮
            if (!string.IsNullOrEmpty(Request.QueryString["close"]))
            {
                int.TryParse(Request.QueryString["close"], out CloseBtnShow);
            }
            ///是否传递的提示信息
            if (!string.IsNullOrEmpty(Request.QueryString["msg"]))
            {
                Message = Request.QueryString["msg"];
                lblMsg.Text = Message;
            }

            ////如果是主管，则返回列表页，否则刷新当前页
            if (UserRole == "Manager")
            {
                if (Request.UrlReferrer != null)
                {
                    UrlBack = Request.UrlReferrer.ToString();
                }
            }
            else
            {
                UrlBack = Request.Url.ToString();
            }
            
            ShowStatus = opt;
        }

        /// <summary>
        /// 判断是否显示安全考核证（施工，市政，管理端显示）
        /// </summary>
        private void Initial()
        {
            //专家附加信息
            expert.Visible = true;

        }

        /// <summary>
        /// 取得字典数据
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        protected Dictionary<string, string> GetGetDictionary(string type, string condition)
        {
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                return JsonConvert.DeserializeObject<Dictionary<string, string>>(client.GetDictionary(type, condition, CurrentArea));
            }
        }
        
        /// <summary>
        /// 绑定下拉列表
        /// </summary>
        private void BindDropDownList()
        {
            ////性别
            DropSex.DataSource = GetGetDictionary("empsex", "");
            DropSex.DataTextField = "value";
            DropSex.DataValueField = "key";
            DropSex.DataBind();
            DropSex.Items.Insert(0, new ListItem("请选择", "-1"));
            
            ////学历
            DropDegree.DataSource = GetGetDictionary("empdegree", "");
            DropDegree.DataTextField = "value";
            DropDegree.DataValueField = "key";
            DropDegree.DataBind();
            DropDegree.Items.Insert(0, new ListItem("请选择", "-1"));
            
            ////评审资格大
            Dictionary<string,string> postSubDic = GetGetDictionary("postsub", "-1");

            ////专家系统里排除掉【助理级】和【员级】
            if (AppId == "95")
            {
                postSubDic.Remove("04");
                postSubDic.Remove("05");
            }

            DropQual.DataSource = postSubDic;
            DropQual.DataTextField = "value";
            DropQual.DataValueField = "key";
            DropQual.DataBind();
            DropQual.Items.Insert(0, new ListItem("请选择", "-1"));

            ////需要配到字典表
            Dictionary<string, string> postSource = new Dictionary<string, string>();
            postSource.Add("1", "在岗");
            postSource.Add("2", "离岗");
            postSource.Add("3", "退休");
            DropPost.DataSource = postSource;
            DropPost.DataTextField = "value";
            DropPost.DataValueField = "key";
            DropPost.DataBind();
            DropPost.Items.Insert(0, new ListItem("请选择", "-1"));

        }

       
        #endregion

        #region 审核状态和可编辑状态

        /// <summary>
        /// 根据审核状态判断可编辑状态
        /// </summary>
        private void CheckFlowCode()
        {
            //打印按钮显示
            if (UserRole == "Manager")
            {
              
                //corpRelation.Visible = true;////专家关系单位
                expertRelation.Visible = true;////关系专家
            }
            //审核状态文字显示
            if (hdTypeFlag.Value.Trim() == "-1")
            {
                ShenheDiv.Visible = true;
            }
            ////页面显示状态
            if (ShowStatus == 2)
            {
                EditStatus = 1;////不可编辑
                return;
            }
            ////管理人员
            if (!CheckEmpManager())
            {
                return;
            }
            ////人员修改验证
            if (hdStatus.Value == "1")
            {
                CheckUserBtnShow();
            }
            else
            {
                CheckDefualtBtnShow();//默认显示
            }
            CheckWindowModel();
        }

        /// <summary>
        /// 管理人员验证
        /// </summary>
        /// <returns></returns>
        private bool CheckEmpManager()
        {

            if (hdTypeFlag.Value.Trim() != "-1")
            {
                //  ShenheDiv.Visible = false;//审核状态
                if (UserRole == "Manager")
                {
                    EditStatus = 1;////管理端不可编辑
                    return false;
                }
                if (CheckCorpStasus())
                {
                    lblMessage.Visible = true;
                    EditStatus = 1;////不可编辑
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 取得管理人员审核状态
        /// </summary>
        /// <returns></returns>
        private bool CheckCorpStasus()
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var managerGuid = hdEmpGuid.Value;
                var result = JsonConvert.DeserializeObject<ModelService.OperationResult>(client.CheckManagerStatus(CorpUserGuid, hdTypeFlag.Value.Trim(), managerGuid, 4, CurrentArea));
                if (!result.Result)
                {
                    //  RadWindowManager1.RadAlert(result.Message, 300, 150, "提示", "");
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 取得人员审核状态组
        /// </summary>
        /// <returns>返回从添加到审核的所有操作状态集</returns>
        private List<ModelService.OperationResult> GetFlowCodes()
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var result = JsonConvert.DeserializeObject<ModelService.OperationResult>(client.GetFlowCodes(CorpUserGuid, hdEmpGuid.Value.Trim(), 7, CurrentArea));
                if (!result.Result)
                {
                    //RadWindowManager1.RadAlert("人员信息异常，无法完成操作！", 300, 150, "提示", "");
                    return null;
                }
                //状态结果集
                return JsonConvert.DeserializeObject<List<ModelService.OperationResult>>(result.ReturnValue.ToString());
            }
        }

        /// <summary>
        /// 默认控制按钮显示及可编辑状态
        /// </summary>
        /// <param name="status"></param>
        private void CheckDefualtBtnShow()
        {
            ////可以编辑
            EditStatus = 0;
            ShenheDiv.Visible = false; //审核状态
            btnImgDiv.Visible = true;//上传
            btnImgCardDiv.Visible = true;//图片上传
            btnImgPostDiv.Visible = true;//图片上传
            btnImgExtDiv.Visible = true;//图片上传
            PersonKHbtnDiv.Visible = true;
            PersonZCbtnDiv.Visible = true;
            PersonIDbtnDiv.Visible = true;
            btnSaveDiv.Visible = true;//保存
            zgBtnDiv.Visible = true;//证书
            workBtnDiv.Visible = true;//工作经历
            btnEmpDiv.Visible = true;//上报
            mainSpecBtnDiv.Visible = true;//专家主专业
            etcSpecBtnDiv.Visible = true;//专家辅专业
            etcSpecBtnDiv2.Visible = true;//专家辅专业2
            corpRelation.Visible = true;//专家关系单位
            expertRelation.Visible = true;//关系专家
            signBtnArea.Visible = true;//专家签名按钮区

            specAddMainDiv.Visible = true;//专家专业添加
            specAddEtcDiv.Visible = true;
            specAddEtc2Div.Visible = true;
            if (!string.IsNullOrEmpty(hdManual.Value))
            {
                scBtnDiv.Visible = true;//职业手册
            }

            //empManual.Visible = false;//职业手册不可添加修改
        }

        /// <summary>
        /// 用户按钮显示及可编辑状态
        /// </summary>
        private void CheckUserBtnShow()
        {
            ////不可编辑
            EditStatus = 1;
            List<ModelService.OperationResult> resultList = GetFlowCodes();
            if (resultList == null)
            {
                return;
            }
            //企业端
            if (UserRole == "User" || UserRole == "Expert")
            {
                //可以编辑
                if (resultList[1].Result)
                {
                    CheckDefualtBtnShow();
                }
                //可以上报
                if (resultList[4].Result)
                {
                    btnEmpDiv.Visible = true;//上报
                    btnDownDiv.Visible = false;////只有上报以后才能导出pdf
                }
                if (EditStatus == 1)
                {
                    //lblMessage.Visible = true;//不可编辑提示
                    //GetEmpFlowStatus();
                }
            }
            else
            {
                //管理端
                if (resultList[5].Result || resultList[6].Result)
                {
                    btnEmpAudit.Visible = true;//审核
                }
            }

        }

        ///// <summary>
        ///// 返回人员在各市场的审核状态
        ///// </summary>
        //private void GetEmpFlowStatus()
        //{
        //    using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
        //    {
        //        var result = JsonConvert.DeserializeObject<List<ModelService.FlowStatus>>(client.GetEmpFlowStatus(hdEmpGuid.Value.Trim(), CurrentArea));
        //        if (result == null && result.Count == 0)
        //        {
        //            lblMessage.Visible = true;//不可编辑提示数据异常
        //            return;
        //        }
        //        //显示提示div
        //        EmpEditTip.Visible = true;
        //        RepEmpTip.DataSource = result;
        //        RepEmpTip.DataBind();
        //    }
        //}

        /// <summary>
        /// 窗口模式按钮显示
        /// </summary>
        private void CheckWindowModel()
        {
            //企业端管理人员
            if (hdTypeFlag.Value.Trim() != "-1" || WindowModel > 0)
            {
                btnEmpDiv.Visible = false;  ////无上报功能
            }
            if (CloseBtnShow > 0)
            {
                btnEmpClosediv.Visible = true;//显示关闭按钮
            }
        }

        #endregion
    }
}
